// Copyright 2011 Bryan McKelvey, MIT License

/**
 * @fileoverview The Settings singleton and the methods available to it
 * @author bryan.mckelvey@gmail.com (McKelvey Bryan)
 */

/**
 * This class represents a collection of settings
 * @constructor
 */
var Settings = (function() {
  /**
   * A collection of default values from populating currently unassigned settings
   * @const
   * @type Object.<string, boolean>
   */
  var DEFAULTS = {
    facebook: true,
    twitter: true
  }
  
  /** The collection of settings for use in passing as JSON */
  var items = {};

  return {
		/**
		 * Returns all settings items
		 * @return {Object.<string,boolean>} All settings items
		 */
    all: function() {
      return items;
    },
    
		/**
		 * Returns a settings item by its key
		 * @param {string} key The key of the value to retrieve
		 * @return {boolean} The value of the setting
		 */
    get: function(key) {
      return items[key]
    },
    
		/**
		 * Loads settings from local storage, setting defaults if necessary and deleting deprecated
     * settings
		 */
    load: function() {
      items = {};
      for (var key in localStorage) {
        if (key in DEFAULTS) {
          try {
            items[key] = JSON.parse(localStorage);
          } catch (e) { }
        }
      }
      
      for (var key in DEFAULTS) {
        items[key] = items[key] || DEFAULTS[key];
      }
    },
    
		/** Saves settings to local storage */
    save: function() {
      for (var key in settings) {
        localStorage[key] = JSON.stringify(items[key]);
      }
    },
    
		/**
		 * Sets and saves a setting by its key
     * @param {string} key The key of the value to set
     * @param {boolean} value The value to set
		 */
    set: function(key, value) {
      items[key] = value;
      localStorage[key] = JSON.stringify(value);
    }
  }
})();